<template>
    <div>
      <n-card :bordered="false">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
      </n-card>
      <n-card :bordered="false" class="mt-3">
        
        <BasicTable
          :columns="columns"
          :request="loadDataTable"
          :row-key="(row) => row.modelId"
          :checkable = "true"
          ref="actionRef"
          :actionColumn="actionColumn"
          @update:checked-row-keys="onCheckedRow"
          :scroll-x="1300"
          :striped="true"
        >
          <template #tableTitle>
            <n-button type="primary" @click="addTable">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新增
            </n-button>
            <n-button type="error" @click="batchDelete" :disabled="!checkedIds.length">
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
          </template>
  
          <template #toolbar> </template>
        </BasicTable>
  
        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新增模型">
          <n-form
            :model="formParams"
            :rules="rules"
            ref="formRef"
            label-placement="left"
            :label-width="100"
            class="py-4"
          >
            <n-form-item label="型号名称" path="modelName">
              <n-input placeholder="请输入型号名称" v-model:value="formParams.modelName" />
            </n-form-item>
            <n-form-item label="生产厂家" path="prodFactory">
              <n-input placeholder="请输入生产厂家" v-model:value="formParams.prodFactory" />
            </n-form-item>
            <n-form-item label="工作电压" path="workingVoltage">
              <n-input placeholder="请输入工作电压" v-model:value="formParams.workingVoltage" />
            </n-form-item>
            <n-form-item label="电池寿命" path="batteryLife">
              <n-input-number placeholder="请输入电池寿命" v-model:value="formParams.batteryLife" />
            </n-form-item>
            <n-form-item label="工作温度" path="workingTemperature">
              <n-input placeholder="请输入工作温度" v-model:value="formParams.workingTemperature" />
            </n-form-item>
            <n-form-item label="防护等级" path="ipRating">
              <n-input placeholder="请输入防护等级" v-model:value="formParams.ipRating" />
            </n-form-item>
            <n-form-item label="备注" path="remark">
              <n-input type="textarea" placeholder="请输入备注" v-model:value="formParams.remark" />
            </n-form-item>
          </n-form>
  
          <template #action>
            <n-space>
              <n-button @click="() => (showModal = false)">取消</n-button>
              <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
            </n-space>
          </template>
        </n-modal>
      </n-card>
    </div>
  </template>
  
  <script lang="ts" setup>
    import { h, reactive, ref } from 'vue';
    import { BasicTable, TableAction } from '@/components/Table';
    import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
    import { PlusOutlined, DeleteOutlined } from '@vicons/antd';
    import { useMessage } from 'naive-ui';
    import { type FormRules } from 'naive-ui';
    import { 
      getShoeModelList, 
      addShoeModel, 
      updateShoeModel, 
      deleteShoeModel, 
      batchDeleteShoeModel 
    } from '@/api/business/shoeModel';
    import { columns } from './modelColumns';
  
    interface ModelData {
      modelId: string;
      modelName: string;
      prodFactory: string;
      workingVoltage: string;
      batteryLife: number;
      workingTemperature: string;
      ipRating: string;
      remark: string;
      createTime: string;
      createName: string;
    }
  
    const message = useMessage();
  
    const rules: FormRules = {
      modelName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入型号名称',
      },
      prodFactory: {
        required: false,
        trigger: ['blur', 'input'],
        message: '请输入生产厂家',
      },
      workingVoltage: {
        required: false,
        trigger: ['blur', 'input'],
        message: '请输入工作电压',
      },
      batteryLife: {
        required: false,
        type: 'number',
        trigger: ['blur', 'change'],
        message: '请输入电池寿命',
      },
      workingTemperature: {
        required: false,
        trigger: ['blur', 'input'],
        message: '请输入工作温度',
      },
      ipRating: {
        required: false,
        trigger: ['blur', 'input'],
        message: '请输入防护等级',
      },
      remark: {
        required: false,
        trigger: ['blur', 'input'],
        message: '请输入备注',
      }
    };
  
    // 搜索表单配置
    const schemas: FormSchema[] = [
      {
        field: 'modelName',
        component: 'NInput',
        label: '型号名称',
        componentProps: {
          placeholder: '请输入型号名称进行搜索',
        },
      }
    ];
  
    const formRef: any = ref(null);
    const actionRef = ref();
  
    const showModal = ref(false);
    const formBtnLoading = ref(false);
    const checkedIds = ref<string[]>([]);
  
    const formParams = reactive({
      modelId: '',
      modelName: '',
      prodFactory: '',
      workingVoltage: '',
      batteryLife: undefined,
      workingTemperature: '',
      ipRating: '',
      remark: ''
    });
  
    const actionColumn = reactive({
      width: 150,
      title: '操作',
      key: 'action',
      fixed: 'right',
      render(record) {
        return h(TableAction as any, {
          style: 'button',
          actions: [
            {
              label: '编辑',
              onClick: handleEdit.bind(null, record),
              ifShow: () => {
                return true;
              },
            },
            {
              label: '删除',
              onClick: handleDelete.bind(null, record),
              ifShow: () => {
                return true;
              },
            },
          ]
        });
      },
    });
  
    const [register, { getFieldsValue }] = useForm({
      gridProps: { cols: '1 s:1 m:1 l:1 xl:1 2xl:1' },
      labelWidth: 100,
      schemas,
    });
  
    function addTable() {
      // 清空表单
      Object.assign(formParams, {
        modelId: '',
        modelName: '',
        prodFactory: '',
        workingVoltage: '',
        batteryLife: undefined,
        workingTemperature: '',
        ipRating: '',
        remark: ''
      });
      showModal.value = true;
    }
  
    // 参考role.vue的请求方式
    const loadDataTable = async (res) => {
      let _params = {
        ...getFieldsValue(),
        ...res,
      };
      
      // 清理空参数，参考role.vue的方式
      Object.keys(_params).forEach(key => {
        if (_params[key] === '' || _params[key] === null || _params[key] === undefined) {
          delete _params[key];
        }
      });
  
      // 使用封装好的API方法，类似role.vue中的getRoleList
      const data = await getShoeModelList(_params);
      // 这里使用了data.list去修复和适配框架;解决数据加载问题
      return {
        list: data.records,
        total: data.total,
      }
      
    };
  
    function onCheckedRow(rowKeys) {
      checkedIds.value = rowKeys;
    }
  
    function reloadTable() {
      actionRef.value.reload();
    }
  
    function confirmForm(e) {
      e.preventDefault();
      formBtnLoading.value = true;
      formRef.value.validate(async (errors) => {
        if (!errors) {
          try {
            const params = { ...formParams };
            // 清理空参数
            Object.keys(params).forEach(key => {
              if (params[key] === '' || params[key] === null || params[key] === undefined) {
                delete params[key];
              }
            });
            
            let result;
            // 根据是否有modelId判断是新增还是编辑
            if (params.modelId) {
              // 编辑接口
              result = await updateShoeModel(params);
            } else {
              // 新增接口
              result = await addShoeModel(params);
            }
            
            if (result.code === 0) {
              message.success(params.modelId ? '编辑成功' : '新增成功');
              setTimeout(() => {
                showModal.value = false;
                reloadTable();
              }, 500);
            } else {
              message.error(result.errMsg || '操作失败');
            }
          } catch (error) {
            message.error('操作失败: ' + error.message);
          }
        } else {
          message.error('请填写完整信息');
        }
        formBtnLoading.value = false;
      });
    }
  
    function handleEdit(record: ModelData) {
      // 将record数据填充到表单
      Object.assign(formParams, record);
      showModal.value = true;
    }
  
    async function handleDelete(record: ModelData) {
      try {
        const result = await deleteShoeModel({ modelId: record.modelId });
        
        if (result.code === 0) {
          message.success('删除成功');
          reloadTable();
        } else {
          message.error(result.errMsg || '删除失败');
        }
      } catch (error) {
        message.error('删除失败: ' + error.message);
      }
    }
  
    async function batchDelete() {
      if (!checkedIds.value.length) {
        message.warning('请先选择要删除的项');
        return;
      }
      
      try {
        const result = await batchDeleteShoeModel({ modelIds: checkedIds.value });
        
        if (result.code === 0) {
          message.success(`批量删除 ${checkedIds.value.length} 项成功`);
          checkedIds.value = [];
          reloadTable();
        } else {
          message.error(result.errMsg || '批量删除失败');
        }
      } catch (error) {
        message.error('批量删除失败: ' + error.message);
      }
    }
  
    function handleSubmit(values: Recordable) {
      console.log(values);
      reloadTable();
    }
  
    function handleReset(values: Recordable) {
      console.log(values);
      reloadTable();
    }
  </script>
  
  <style lang="less" scoped></style>